<template>
  <el-row>
    <el-col :span="24" :xs="24">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="queryParams.configName" placeholder="请输入参数名称" clearable size="small" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="queryParams.configKey" placeholder="请输入参数键名" clearable size="small" style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
     <!--   <el-form-item label="系统内置" prop="configType">
          <el-select v-model="queryParams.configType" placeholder="系统内置" clearable size="small">
            <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:config:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['system:config:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['system:config:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['system:config:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-refresh" size="mini" @click="handleClearCache"
            v-hasPermi="['system:config:remove']">清理缓存</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange" :height="maxHeight">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="参数主键" align="center" prop="configId" />
        <el-table-column label="参数名称" align="center" prop="configName" :show-overflow-tooltip="true" />
        <el-table-column label="参数键名" align="center" prop="configKey" :show-overflow-tooltip="true" />
        <el-table-column label="参数键值" align="center" prop="configValue" />
        <el-table-column label="系统内置" align="center" prop="configType" :formatter="typeFormat" />
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:config:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:config:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>20" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-col>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择模块" prop="moduleId" v-if="openStatus=='configPage'">
          <el-select v-model="selectValue" class="dick-select" placeholder="请选择" @change="dictChange"
            :disabled="butChange=='2'" style="width: 100%;">
            <el-option v-for="item in dictModule" :key="item.id" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择单据" class="dick-select" prop="value" v-if="openStatus=='treePage'">
          <el-cascader v-model="value" :options="formTree" ref="classTree" :props="classProps" @change="handleChange"
            class="cas-input" :disabled="butChange=='2'" style="width: 100%;"></el-cascader>
        </el-form-item>
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="form.configType">
            <el-radio v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </el-row>


</template>

<script>
  import {
    listConfig,
    getConfig,
    delConfig,
    addConfig,
    updateConfig,
    exportConfig,
    clearCache,
    listModule
  } from "@/api/system/config";
  import {
    getTreeData,
    getEcho,
    supParent,
    selectNode,
    getCurrentNode,
    setCurrentNode
  } from "./utils/form.js"
  export default {
    name: "Config",
    data() {
      var checkModule = (rule, value, callback) => {
        if (this.selectValue == null) {
          return callback(new Error(''));
        } else {
          callback();
        }

      };
      var checkValue = (rule, value, callback) => {
        if (this.value.length == 0) {
          return callback(new Error(''));
        } else {
          callback();
        }
      };
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 最大高度
        maxHeight: null,
        //点击状态
        isCurrent: null,
        // 参数表格数据
        configList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 类型数据参数
        typeOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          configName: undefined,
          configKey: undefined,
          configType: undefined,
        },
        // 表单参数
        form: {
          moduleId: "",
          formId: ""
        },
        //选择单据回显信息
        value: [],
        selectValue: null,
        //单据选择配置
        classProps: {
          children: "children",
          label: "formName",
          value: "formCode",
          checkStrictly: true
        },
        //按钮状态
        butChange: "",
        selectValue: null,
        // 表单校验
        rules: {
          value: [{
            required: true,
            validator: checkValue,
            trigger: 'change'
          }],
          moduleId: [{
            required: true,
            message: "参数名称不能为空",
            trigger: "blur"
          }],
          configName: [{
            required: true,
            message: "参数名称不能为空",
            trigger: "blur"
          }],
          configKey: [{
            required: true,
            message: "参数键名不能为空",
            trigger: "blur"
          }],
          configValue: [{
            required: true,
            message: "参数键值不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    props: {
      moduleId: {
        type: String,
        default: ""
      },
      formId: {
        type: String,
        default: ""
      },
      formId: {
        type: Number,
        default: null
      },
      openStatus: {
        type: String,
        default: ""
      },
      dictModule: {
        type: Array,
        default () {
          return []
        }
      },
      formTree: {
        type: Array,
        default () {
          return []
        }
      }
    },
    created() {
      if (this.openStatus == "configPage") {
        if (this.moduleId !== "") {
          this.selectValue = this.moduleId;
          this.queryParams.moduleId = this.moduleId;
        } else {
          this.queryParams.moduleId = "";
        }
        this.getList();
        this.getDicts("sys_yes_no").then(response => {
          this.typeOptions = response.data;
        });
      } else if (this.openStatus == "treePage") {
        if (this.formId !== null) {
          this.queryParams.formId = this.formId;
          this.form.formId = this.formId;
        } else {
          this.queryParams.formId = "";
        }
        this.getList();
        this.getDicts("sys_yes_no").then(response => {
          this.typeOptions = response.data;
        });
      }

    },
    methods: {
      /** 查询参数列表 */
      getList() {
        this.loading = true;
        listConfig(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.configList = response.rows;
          this.total = response.total;
          this.loading = false;
          if (this.configList.length >= 20) { //条数总数大于显示出现滚动条
            this.maxHeight = (`${document.documentElement.clientHeight}` - 270);
          } else {
            this.maxHeight = ""
          }
        });
      },

      // 参数系统内置参数翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.configType);
      },

      // 模块下拉框选择
      dictChange(value) {
        this.form.moduleId = value;
      },

      // 单据选择回显结果
      handleChange(value) {
        value = value.join(""); //转换成字符串，用于传值后台
        this.queryParams.formId = this.$refs['classTree'].getCheckedNodes()[0].data.formId; //赋值formId
        this.form.formId  = this.$refs['classTree'].getCheckedNodes()[0].data.formId;
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        if (this.openStatus == "treePage") {
          this.resetSelector();
        }

      },

      //关闭
      close() {
        this.open = false;
        this.reset();
        if (this.openStatus == "treePage") {
          this.resetSelector();
        }
      },

      // 表单重置
      reset() {
        this.form = {
          configId: undefined,
          configName: undefined,
          configKey: undefined,
          configValue: undefined,
          configType: "Y",
          remark: undefined,
          moduleId: this.moduleId,
          formId: this.formId
        };
        this.value = [];
        this.resetForm("form");
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        if (this.openStatus == "configPage") {
          this.form.moduleId = "";
          this.queryParams.moduleId = "";
        } else {
          this.form.formId = "";
          this.queryParams.formId = "";
        }
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.butChange = "1"
        this.reset();
        this.open = true;
        this.title = "添加参数";
        if (this.formId !== null && this.formId !== "") {
          this.viewEcho(this.form.formId)
        }

      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.configId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.butChange = '2';
        const configId = row.configId || this.ids
        getConfig(configId).then(response => {
          this.form = response.data;
          if (this.openStatus == "configPage") {
            this.selectValue = response.data.moduleId;
               this.open = true;
          } else if (this.openStatus == "treePage") {
            this.viewEcho(row.formId).then(() => {
              this.open = true;
            })
          }

          this.title = "修改参数";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {

          if (valid) {
            if (this.form.configId != undefined) {
              console.log(this.form)
              updateConfig(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addConfig(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const configIds = row.configId || this.ids;
        this.$confirm('是否确认删除参数编号为"' + configIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delConfig(configIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所选参数数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportConfig(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 清理缓存按钮操作 */
      handleClearCache() {
        clearCache().then(response => {
          this.msgSuccess("清理成功");
        });
      },
      // 单据回显
      viewEcho(id) {
        return new Promise((resolve, reject) => {
          let parentArr = [], //用于储存父类单据信息
            childrenArr = []; ////用于储存子类单据信息
          getEcho(id, this.formTree, parentArr, childrenArr).then((res) => {
            setTimeout(() => {
              let success = [];
              for (let i = 0; i < res.length; i++) {
                if (success.indexOf(res[i]) === -1) {
                  success.push(res[i])
                }
              }
              let getNode = JSON.parse(JSON.stringify(success)) //拷贝vuex信息，避免影响源数据
              getNode.forEach(v => {
                if (v.ancestors.indexOf(",") > -1) { //是否是子单据
                  v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
                } else {
                  v.ancestors = 1;
                }
              })
              getNode.sort((a, b) => { //排序得到正常的单据顺序，用于得到form
                return a.ancestors - b.ancestors
              })
              let getCode = [];
              getNode.forEach(code => {
                getCode.push(code.formCode);
              })
              this.value = getCode; //对话框分类回显
            }, 0)
          });
          resolve()
        })

      },
      //解决级联选择器回显高亮异常问题
      resetSelector() {
        if (this.$refs.classTree) {
          this.$refs.classTree.$refs.panel.activePath = [];
          this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
        }
      },
    }
  };
</script>
<style lang="scss">
  .dick-select {
    input {
      color: #1890FF !important;
    }
  }

  .config-box {
    .none-data li {
      color: #999;
      justify-content: center;
      padding-top: 10px !important;
    }

    .dict-module {
      .dic-t {
        margin-right: 20px;
        border: 1px solid #eee;
        text-align: center;
        padding-bottom: 10px;
      }

      h3 {
        font-size: 15px;
        font-weight: normal;
        border-bottom: 1px solid #eee;
        padding: 10px;
        margin: 0;
      }

      ul {
        margin: 0;
        padding: 0;
        margin-left: 15px;
      }

      ul li {
        label {
          width: 5px;
          height: 5px;
          display: inline-block;
          background: #ccc;
          vertical-align: middle;
          margin-right: 10px;
        }

        display: flex;
        align-items: center;
        padding: 5px;
        list-style: none;
        cursor: pointer;
        font-size: 14px;
        color: #606266;
        text-align: left;

      }

      // 高亮
      .active {
        color: #1890FF;

        label {
          background: #1890FF;
        }
      }
    }
  }
</style>
